public class runVol {
    //添加volatile之后此变量的值变化可以被所有线程看到
    private static volatile boolean flag;
    public static void main(String[] args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getId()+"在运行");
                    while(!flag){}
                    System.out.println(Thread.currentThread().getId()+"flag值被改变");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Thread.sleep(2000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    System.out.println(Thread.currentThread().getId()+"修改flag值");
                    flag = true;
                    System.out.println(Thread.currentThread().getId()+"修改完成");
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }).start();

    }

}
